package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 获取用户姓名服务类
 * @author zhengjd
 * @date 2020/4/11 20:32
 */
@RestController
@RequestMapping("/user")
public class UsernameController {


    @Reference
    private UserService userService;
    /**
     * 获取用户名
     * @return
     */
    @RequestMapping("/getUsername")
    public Result getUsername(){
        try {
            //根据SecurityContext获取认证授权类中返回的User对象
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_USERNAME_FAIL);
        }
    }

}
